package com.me.common.util.event;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.collections.CollectionUtils;

/**
 * java 事件发布：事件发布中心
 *
 * @author ME
 * @date   2020/5/10
 */
public class EventPublishCenter {

    private static final Map<String, List<MyEventListener>> EVENT_PUBLISH_CENTER = new ConcurrentHashMap<>(16);

    /**
     * 发布事件，并触发事件监听
     *
     * @param event 事件对象
     */
    public static void publish(EventObject event) {
        List<MyEventListener> listeners = EVENT_PUBLISH_CENTER.get(event.getSource().getClass().getName());
        if (CollectionUtils.isNotEmpty(listeners)) {
            for (MyEventListener listener : listeners) {
                listener.onEvent(event);
            }
        }
    }

    /**
     * 某个监听者订阅指定事件
     *
     * @param event 事件对象
     * @param listener 监听者
     */
    public static void subscribe(EventObject event, MyEventListener listener) {
        String name = event.getSource().getClass().getName();
        List<MyEventListener> listeners = EVENT_PUBLISH_CENTER.computeIfAbsent(name, k -> Collections.synchronizedList(new LinkedList<>()));
        if (!listeners.contains(listener)) {
            listeners.add(listener);
        }
    }

    /**
     * 某个监听者取消订阅指定事件
     *
     * @param event 事件对象
     * @param listener 监听者
     */
    public static void unsubscribe(EventObject event, MyEventListener listener) {
        List<MyEventListener> listeners = EVENT_PUBLISH_CENTER.get(event.getSource().getClass().getName());

        if (listeners != null) {
            listeners.remove(listener);
        }
    }

}
